package com.szmg.wishwalls.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
	
	public static String httpPost(HttpClient httpclient,List<NameValuePair> formparams,String url){
		System.out.println("===================");
		for(NameValuePair p :formparams){
			System.out.println("------"+p.getName()+"="+p.getValue());
		}
		System.out.println("===================");
		//创建httppost
		HttpPost httppost = new HttpPost(url);
		
		UrlEncodedFormEntity uefEntity;
		String responeStr = "";
		try {
			
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			log.info("executing request " + httppost.getURI());
			HttpResponse response;
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responeStr = EntityUtils.toString(entity, "UTF-8");
				log.info("------------------------" + responeStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responeStr;
	}
	
	
	public static String httpGet(String url,HttpClient httpclient){
		HttpGet Httpget = new HttpGet(url);
		String responseXml = null;
		try {
			Httpget.addHeader("Content-Type", "text/xml");
			HttpResponse response;
			response = httpclient.execute(Httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseXml = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			log.error("HttpClientUtil UnsupportedEncodingException error!",e);
		} catch (ClientProtocolException e) {
			log.error("HttpClientUtil ClientProtocolException error!",e);
		} catch (IOException e) {
			log.error("HttpClientUtil IOException error!",e);
		}finally{
			httpclient.getConnectionManager().shutdown();
		}
		log.debug("===========response str ="+responseXml);
		
		return responseXml;
	}
}
